import logging
import traceback
import uuid
import pickle
import os
import json
import chardet
import pandas as pd

from typing import List
from PySide6.QtCore import QThread, Signal

logging.basicConfig(
    format='%(asctime)s %(levelname)s %(filename)s line%(lineno)d: %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)


class PackReader(QThread):

    except_signal = Signal(str)
    progress = Signal(int)
    file_name = Signal(bytes)

    def __init__(
        self, device_config: dict, bms_config: dict, headers: list, parent=None
    ):
        """检查是否设备里面的
        Args:
            selected_files: 被选中的需要读取的csv文件列表
            config (dict): 配置字典，从配置文件中加载
            parent (QObject): 父对象，默认为None

        Returns:
            从众多csv文件中，仅仅提取关键列数据，将合并后的csv文件，写入到本地data目录下，返回文件名，供
            下一步的数据筛选计算使用
        """
        super().__init__(parent)
        self.headers = headers
        self.device_config = device_config
        self.bms_config = bms_config

    def _read_usecols_from_config(self) -> List[str]:
        """从数据处理方案中获取需要读取的列"""
        use_columns = []
        # 设备配置里面，本身需要读取的列
        for tag, column in self.device_config.items():
            if tag in ['name', 'ch_key', 'dch_key', 'stew_key']:
                continue
            if column:
                use_columns.extend(column.split("、"))
        # BMS信号配置里面需要读取的列
        for tag, column in self.bms_config.items():
            if column:
                use_columns.extend(column.split("、"))
        return list(set(use_columns))

    def run(self):
        self.progress.emit(0)
        try:
            self.merge_columns()
        except Exception as e:
            # 获取错误的详细信息并发送信号
            error_message = traceback.format_exc().strip().splitlines()[-1]
            self.except_signal.emit(error_message)
            raise e
        self.progress.emit(100)
